package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/20 18:37
 * 给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在，返回 true ；否则，返回 false
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/subtree-of-another-tree
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class IsSubtree {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            if (compare(pop, subRoot)) {
                return true;
            }
            if (pop.left != null) {
                stack.push(pop.left);
            }
            if (pop.right != null) {
                stack.push(pop.right);
            }
        }
        return false;
    }

    private boolean compare(TreeNode pop, TreeNode subRoot) {
        if (pop == null && subRoot == null) {
            return true;
        } else if(pop != null && subRoot == null){
            return false;
        } else if (pop == null && subRoot != null) {
            return false;
        } else if (pop.val != subRoot.val) {
            return false;
        } else {
            return compare(pop.left, subRoot.left) && compare(pop.right, subRoot.right);
        }
    }

    public static void main(String[] args) {

    }
}
